package com.ztgf.order.service.async;

import com.alibaba.fastjson.JSON;
import com.ztgf.common.constant.Result;
import com.ztgf.common.utils.CustomizeUtil;
import com.ztgf.message.model.bo.MessageAnnouncementSaveBO;
import com.ztgf.message.model.constant.MessageTopicType;
import com.ztgf.message.model.dto.ResponseDTO;
import com.ztgf.message.model.enums.MessageEnum;
import com.ztgf.message.model.service.IKafkaProducerService;
import com.ztgf.order.models.bo.pay.PayOrderSaveBO;
import com.ztgf.order.models.dto.OrderInfoDTO;
import com.ztgf.order.models.service.IOrderInfoService;
import com.ztgf.order.models.service.async.IAsyncOrderService;
import com.ztgf.order.models.service.pay.IPayService;
import com.ztgf.order.models.vo.pay.PayOrderVO;
import com.ztgf.shopping.models.service.shop.IShopInfoService;
import com.ztgf.shopping.models.vo.shop.ShopInfoVO;
import com.ztgf.sms.models.bo.SmsInfoSaveBO;
import com.ztgf.sms.models.service.ISmsInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;

import java.util.Arrays;
import java.util.List;

@DubboService
@Slf4j
public class AsyncOrderServiceImpl implements IAsyncOrderService {

    @DubboReference
    private IKafkaProducerService kafkaProducerService;

    @DubboReference
    private ISmsInfoService smsInfoService;

    @DubboReference
    private IShopInfoService shopInfoService;

    @Autowired
    private IPayService payService;

    @Autowired
    @Lazy
    private IOrderInfoService orderInfoService;


    @Async
    @Override
    public void sendOrderNotice(Long shopId, Long orderId) {
        //发送通知消息
        sendOrderMessage(Arrays.asList(shopId));
        //发送站内信
        sendWebMessageInChangeOrderStatus(shopId, 2, orderId);
    }

    /**
     * 发送短信
     *
     * @param shopIdList 店铺idList
     */
    public void sendOrderMessage(List<Long> shopIdList) {
        try {
            log.info("0-------sendMessage---------shopIdList:"+shopIdList);
            List<ShopInfoVO> shopInfoVOS = shopInfoService.getByShopIds(shopIdList);
            SmsInfoSaveBO smsInfoSaveBO = new SmsInfoSaveBO();
            for (ShopInfoVO shopInfoVO : shopInfoVOS) {
                smsInfoSaveBO.setMobile(shopInfoVO.getMobile());
                smsInfoService.saveOrderStatus(smsInfoSaveBO);
            }
        } catch (Exception e) {
            log.error("发送短信错误信息:{}", e.getMessage());
        }
    }

    public void sendWebMessageInChangeOrderStatus(Long shopId, int type, Long orderId) {
        try {
            OrderInfoDTO orderInfoDTO = orderInfoService.selectById(orderId);
            log.info("0--------sendWebMessageInChangeOrderStatus--------orderId:"+orderInfoDTO.getPurchaseOrderType());
            ResponseDTO responseDTO = new ResponseDTO();
            MessageAnnouncementSaveBO messageAnnouncementSaveBO = new MessageAnnouncementSaveBO();
            messageAnnouncementSaveBO.setJumpType(MessageEnum.ORDER_STATUS_CHANGE.getCode() + "");
            messageAnnouncementSaveBO.setType(MessageEnum.SYS_MESSAGE.getCode());
            messageAnnouncementSaveBO.setTitle("您有一条订单状态改变，请去查看");
            messageAnnouncementSaveBO.setContent("您有一条订单状态改变，请去查看");
            messageAnnouncementSaveBO.setShopId(shopId);
            messageAnnouncementSaveBO.setShopType(type);
            messageAnnouncementSaveBO.setTextType(1);
            messageAnnouncementSaveBO.setKey(orderId + "");

            if(null != orderInfoDTO.getPurchaseOrderType()){
                messageAnnouncementSaveBO.setPurchaseOrderType(orderInfoDTO.getPurchaseOrderType());//询盘订单或普通订单
            }else{
                messageAnnouncementSaveBO.setPurchaseOrderType(0);//普通订单
            }
            responseDTO.setMessageId(shopId + "");
            responseDTO.setData(messageAnnouncementSaveBO);
            log.info("4----------------orderId:"+JSON.toJSONString(responseDTO));
            kafkaProducerService.senMessage(JSON.toJSONString(responseDTO), MessageTopicType.COMMENT_MESSAGE_TOPIC);
        } catch (Exception e) {
            log.error("发送站内信错误信息:{}", e.getMessage());
        }
    }

    @Async
    @Override
    public void sendPurchaseNotice(Long shopId,Long purchaseId) {
        //发送通知消息
        sendMessage(Arrays.asList(shopId));
        //发送站内信  1买家 2卖家
        sendWebMessage(shopId, 1,purchaseId);
    }

    @Override
    public void sendSms(Long shopId, String content, Integer type) {

        List<ShopInfoVO> shopInfoVOS = shopInfoService.getByShopIds(Arrays.asList(shopId));
        for (ShopInfoVO shopInfoVO : shopInfoVOS) {
            SmsInfoSaveBO bo = new SmsInfoSaveBO();
            bo.setMobile(shopInfoVO.getMobile());
            bo.setContent(content);
            bo.setType(type);
            try {
                smsInfoService.save(bo);
            } catch (Exception e) {
                log.error("发送短信错误信息:{}", e.getMessage());
            }
        }


    }

    @Override
    @Async
    public void sendOrderSms(Long shopId, String content) {
        sendSms(shopId, content, 1);
    }


    /**
     * 砍价通知（短信）
     * @param shopId
     */
    @Override
    public void sendMessage(List<Long> shopId) {
        try {
            List<ShopInfoVO> shopInfoVOS = shopInfoService.getByShopIds(shopId);
            SmsInfoSaveBO smsInfoSaveBO = new SmsInfoSaveBO();
            for (ShopInfoVO shopInfoVO : shopInfoVOS) {
                smsInfoSaveBO.setMobile(shopInfoVO.getMobile());
                smsInfoService.sendMessageByPurchase(smsInfoSaveBO);
            }
        } catch (Exception e) {
            log.error("发送短信错误信息:{}", e.getMessage());
        }
    }

    /**
     * 砍价通知（站内消息）
     * @param shopId
     * @param type
     */
    @Override
    public void sendWebMessage(Long shopId, int type,Long purchaseId) {
        try {
            ResponseDTO responseDTO = new ResponseDTO();
            MessageAnnouncementSaveBO messageAnnouncementSaveBO = new MessageAnnouncementSaveBO();
            messageAnnouncementSaveBO.setJumpType(MessageEnum.PURCHASE_STATUS_CHANGE.getCode() + "");
            messageAnnouncementSaveBO.setType(MessageEnum.SYS_MESSAGE.getCode());
            messageAnnouncementSaveBO.setTitle("您的询盘订单已报价，请去查看");
            messageAnnouncementSaveBO.setContent("您的询盘订单已报价，请去查看");
            messageAnnouncementSaveBO.setKey (purchaseId+"");
            messageAnnouncementSaveBO.setShopId(shopId);
            messageAnnouncementSaveBO.setShopType(type);
            messageAnnouncementSaveBO.setTextType(1);

            responseDTO.setMessageId(shopId + "");
            responseDTO.setData(messageAnnouncementSaveBO);
            kafkaProducerService.senMessage(JSON.toJSONString(responseDTO), MessageTopicType.COMMENT_MESSAGE_TOPIC);
        } catch (Exception e) {
            log.error("发送站内信错误信息:{}", e.getMessage());
        }
    }


    /**
     * 发布询价单（站内信）
     * @param shopIds
     * @param purchaseId
     */
    @Async
    @Override
    public void sendPurchaseWebMessage(List<Long> shopIds, Long purchaseId) {
        if(CustomizeUtil.listIsNotNull (shopIds)){
            //发送站内信  1买家 2卖家
            for (Long shopId: shopIds) {
                purchaseSendWebMessage(shopId,2,purchaseId);
            }
        }
    }

    @Override
    @Async
    public Result<PayOrderVO> savePay(PayOrderSaveBO bo, boolean isCheckToken) {
        return payService.savePay(bo, isCheckToken);
    }


    private void purchaseSendWebMessage(Long shopId, int type, Long purchaseId) {
        try {
            ResponseDTO responseDTO = new ResponseDTO();
            MessageAnnouncementSaveBO messageAnnouncementSaveBO = new MessageAnnouncementSaveBO();
            messageAnnouncementSaveBO.setJumpType(MessageEnum.PUBLISH_PURCHASE.getCode() + "");
            messageAnnouncementSaveBO.setType(MessageEnum.SYS_MESSAGE.getCode());
            messageAnnouncementSaveBO.setTitle("有新的询价单可报价，请去查看");
            messageAnnouncementSaveBO.setContent("有新的询价单可报价，请去查看");
            messageAnnouncementSaveBO.setKey (purchaseId+"");
            messageAnnouncementSaveBO.setShopId(shopId);
            messageAnnouncementSaveBO.setShopType(type);
            messageAnnouncementSaveBO.setTextType(1);

            responseDTO.setMessageId(shopId + "");
            responseDTO.setData(messageAnnouncementSaveBO);
            kafkaProducerService.senMessage(JSON.toJSONString(responseDTO), MessageTopicType.COMMENT_MESSAGE_TOPIC);
        } catch (Exception e) {
            log.error("发送站内信错误信息:{}", e.getMessage());
        }
    }
}
